﻿using Models;
using System.Data.SqlClient;

namespace VirtualGameDAL
{
    public static partial class UserService
    {
        public static bool AddUser(User user)
        {
            string sql = "insert into [User](id, name, password) values(@id, @name, @password)";
            SqlParameter[] para = new SqlParameter[]
            {
                new SqlParameter("@id", user.Id),
                new SqlParameter("@name", user.Name),
                new SqlParameter("@password", user.Password),
            };
            int result = DBHelper.GetScalar(sql, para);
            if (result == -1) return false;
            return true;
        }

        public static User GetUserById(string id)
        {
            string sql = "select * from [User] where id= @id";

            using (SqlDataReader reader = DBHelper.GetReader(sql, new SqlParameter("@id", id)))//使用Using语句，资源可以得到及时释放
            {
                if (reader.Read())
                {
                    User user = new User();
                    user.Id = (string)reader["id"];
                    user.Name = (string)reader["name"];
                    user.Password = (string)reader["password"];

                    reader.Close();//注意关闭reader
                    return user;
                }
                else
                {
                    reader.Close();//没有记录时，也需要关闭reader
                    return null;
                }
            }
        }
    }
}
